package UDPdemo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-10-11
 * Time: 21:04
 */
public class UDPechoClient {
    private DatagramSocket socket = null;
    private String server = null;
    private int port = 0;
    public UDPechoClient(String server, int port) throws SocketException {
        socket = new DatagramSocket();
        this.server = server;
        this.port = port;
    }

    public void start() throws IOException {
        Scanner scan = new Scanner(System.in);
        while (true){
            System.out.println("-> ");//
            String reqpack = scan.next();
            DatagramPacket req = new DatagramPacket(reqpack.getBytes(), reqpack.getBytes().length, InetAddress.getByName(server), port);
            socket.send(req);
            DatagramPacket resp = new DatagramPacket(new byte[4060], 4060);
            socket.receive(resp);
            String resppack = new String(resp.getData(), 0, resp.getLength());//
            System.out.println(resppack);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPechoClient client = new UDPechoClient("127.0.0.1", 9090);
        client.start();
    }

}
